<template>
  <div class="xtx-infinite-loading" ref="target">
    <div class="loading" v-if="loading">
      <span class="img"></span>
      <span class="text">正在加载...</span>
    </div>
    <div class="none" v-if="finished">
      <span class="img"></span>
      <span class="text">{{ finishedText }}</span>
    </div>
  </div>
</template>
<script>
import { useIntersectionObserver } from '@vueuse/core'
import { ref, onBeforeUnmount } from 'vue'
export default {
  name: 'XtxList',
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    finished: {
      type: Boolean,
      default: false
    },
    finishedText: {
      type: String,
      default: '没有更多了'
    }
  },
  setup (props, { emit }) {
    const target = ref(null)
    const { stop } = useIntersectionObserver(
      target,
      ([{ isIntersecting }]) => {
        if (isIntersecting) {
          console.log('进入可视区域')
          // 调用接口获取分页数据
          //   没有加载中，且加载没有完成
          if (!props.loading && !props.finished) {
            emit('load')
          }
        }
      },
      {
        threshold: 0
      }
    )
    // 组件销毁时关闭监听
    onBeforeUnmount(() => {
      stop()
    })
    return { target }
  }
}
</script>
<style lang="less" scoped>
.xtx-infinite-loading {
  .loading {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 200px;
    .img {
      width: 50px;
      height: 50px;
      background: url(~@/assets/images/load.gif) no-repeat center / contain;
    }
    .text {
      color: #999;
      font-size: 16px;
    }
  }
  .none {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 200px;
    .img {
      width: 200px;
      height: 134px;
      background: url(~@/assets/images/none.png) no-repeat center / contain;
    }
    .text {
      color: #999;
      font-size: 16px;
    }
  }
}
</style>
